package cn.edu.ctbu.api01.restcontroller;

import cn.edu.ctbu.api01.domain.Student;
import cn.edu.ctbu.api01.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

@RestController
@RequestMapping("/webapi/student")
public class StudentRestController {

    @Autowired
    StudentService studentService;

    @GetMapping("/list")
    public List<Student> getAll() {
        return studentService.getAll();
    }

    @GetMapping("/get/{id}")
    public ResponseEntity<Student> getById(@PathVariable Integer id) {
        Student student = studentService.getById(id);
        if (student == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        student.setPassword(""); // 隐藏密码
        return new ResponseEntity<>(student, HttpStatus.OK);
    }

    @PostMapping("/add")
    public ResponseEntity<Integer> add(@RequestBody Student student) {
        studentService.save(student);
        return new ResponseEntity<>(student.getId(), HttpStatus.CREATED);
    }

    @PutMapping("/update")
    public ResponseEntity<Student> update(@RequestBody Student student) {
        Student existingStudent = studentService.getById(student.getId());
        if (existingStudent == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        existingStudent.setName(student.getName());
        existingStudent.setSex(student.getSex());
        existingStudent.setScore(student.getScore());
        existingStudent.setNo(student.getNo()); // 更新学号
        Student updatedStudent = studentService.update(existingStudent);
        return new ResponseEntity<>(updatedStudent, HttpStatus.OK);
    }

    @PostMapping("/insert")
    public ResponseEntity<Student> insert(@RequestBody Student student) {
        Student insertedStudent = studentService.insert(student);
        return new ResponseEntity<>(insertedStudent, HttpStatus.CREATED);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Void> delete(@PathVariable Integer id) {
        Student existingStudent = studentService.getById(id);
        if (existingStudent == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        studentService.delete(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    private static final Logger logger = Logger.getLogger(StudentRestController.class.getName());

    @GetMapping("/search")
    public ResponseEntity<List<Student>> search(@RequestParam(required = false) String name,
                                                @RequestParam(required = false) Integer sex) {
        logger.info("Search request received with params - name: " + name + ", sex: " + sex);
        List<Student> result = new ArrayList<>();
        try {
            if (name != null) {
                result = studentService.findByName(name);
            } else if (sex != null) {
                result = studentService.findBySex(sex);
            }
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error occurred during search", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
